import time

import requests
from datetime import datetime
import threading

from logger import log
from settings import settings


def send(measurement, tags, field, value):
    # weather,location=us-midwest temperature=82
    data = measurement + ','

    for key, val in tags.items():
        data += f"{key}={val},"
    data = data[:-1] + ' '  # Remove the last comma and add a space
    data += f"{field}={value}"

    try:
        response = requests.post(settings.vm_write_url, data)
        log.info(f"post status: {settings.vm_write_url}, {data}, {response.status_code}")
    except requests.exceptions.RequestException:
        log.error("metric post error")
    except Exception as e:
        log.error(f"未知错误: {str(e)}", exc_info=True)


def get_date_str(date):
    return date.strftime('%y%m%d%H%M%S')


def online(ms):
    def send_heartbeat():
        while True:
            date = datetime.now()
            full_year = get_date_str(date)
            try:
                send("vsNode", {"deviceName": settings.code}, "online", int(full_year))
            except Exception as e:
                log.error(f"vsNode online 心跳发送失败: {str(e)}", exc_info=True)
            time.sleep(ms)

    # Start the heartbeat in a new thread
    thread = threading.Thread(target=send_heartbeat)
    thread.start()


def init():
    # 在线心跳
    online(10)

# You can use the following to export functions if needed
# __all__ = ['init', 'send']
